package listener_autostart;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import bean.Exam;
import factory.DaoFactory;
import util.Projectdbpool;

public class StartExam {
	
	PreparedStatement preparedStatement = null;
	ResultSet resultSet = null;
	
	public void selectexamtostart() {
		List<Exam> examlist = new ArrayList<>();
		
		
		String Startexamingsql ="select * from examtable where finished is null and autostart = 'on' ";
		try {
			preparedStatement = Projectdbpool.excutePreparedStatement(Startexamingsql);
			/*preparedStatement.setString(1, "on");*/
			resultSet = preparedStatement.executeQuery();
			while (resultSet.next()) {
				Exam e = new Exam();
				e.setExamid(resultSet.getInt("examid"));
				e.setExamname(resultSet.getString("examname"));
				e.setStarttime(resultSet.getString("starttime"));
				e.setAutostart(resultSet.getString("autostart"));
				e.setStarted(resultSet.getString("started"));
				e.setExamcreator(resultSet.getString("examcreator"));
				e.setExamining(resultSet.getString("examining"));
				examlist.add(e);
			}
		}
		catch(Exception e) {
			Projectdbpool.close();
		}
		finally {
			Projectdbpool.close();
		}
		
		
		
		for(int i = 0 ; i < examlist.size() ; i++) {
			
			/*修改时间格式,去掉T*/
			String examtime = examlist.get(i).getStarttime().replaceFirst("T"," ");
			
			if(compareTime(examtime)) {
				DaoFactory.getExamDaoInstance().startexam(examlist.get(i));
			}
		}
	}
	

	public boolean compareTime(String examtime)  {
		
		 boolean  examTime_before_now_Time=false;
		
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
											
		try {
			Date examTime = simpleDateFormat.parse(examtime);
			Date now_Time = new Date();
			if (examTime.before(now_Time)) {
				examTime_before_now_Time = true;
				/*System.out.println("true");*/
			} else {
				examTime_before_now_Time = false;
			/*	System.out.println("false");*/
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		/*考试时间是否在现在时间之前,即为是否到达考试时间*/
		/*到达考试时间返回true未到考试时间返回false*/
		return examTime_before_now_Time;
	}
}